import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:tappay_charge/models/tappay_cart_item.dart';
import 'package:tappay_charge/tappay_charge.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _tappayChargePlugin = TappayCharge();
  final GlobalKey<ScaffoldMessengerState> rootScaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion =
          await _tappayChargePlugin.getPlatformVersion() ?? 'Unknown platform version';
      print(platformVersion);
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });


    final result = await TappayCharge().initTappay(
      appId: 148817,
      appKey: 'app_FqesQKrqozzUEdEk2olWljmWcvcqcJazxTpfGk2VtUV42d8McalPjGGmf4jp',
      isSandBox: true,
    );
    print(result.toJson());
  }

  Future<void> cardPay() async {
    const cardNumber = '4242424242424242';
    const dueMonth = '01';
    const dueYear = '27';
    const ccv = '123';
    final isAvailable = await TappayCharge().validateCard(
      cardNumber: cardNumber,
      dueMonth: dueMonth,
      dueYear: dueYear,
      ccv: ccv,
    );

    if (isAvailable) {

      final result = await TappayCharge().getCardPrime(
        cardNumber: cardNumber,
        dueMonth: dueMonth,
        dueYear: dueYear,
        ccv: ccv,
      );
      print(result.toJson());
      if (result.success) {
        print('Card Prime:${result.prime}');
      }

    }
  }

  Future<void> applePay() async {
    /// 1.初始化
    final initApplePayResult = await TappayCharge().initApplePay(
      merchantName: '微效動能',
      merchantId: 'merchant.com.feibi.smileEnergy',
    );
    print(initApplePayResult.toJson());

    if (initApplePayResult.success) {
      /// 2.发起支付
      final startApplePayResult = await TappayCharge().startApplePay(
        isAmountPending: true,
        // isShowTotalAmount: false,
        cartItems: [
          TappayCartItem(name: 'Banana', price: 100),
          TappayCartItem(name: 'Apple', price: 50),
          TappayCartItem(name: 'Orange', price: 1, isPending: true),
        ],
      );
      print(startApplePayResult.toJson());

      if (startApplePayResult.success) {  /// 支付成功
        final prime = startApplePayResult.prime;
        print('支付成功：$prime');
        // TappayCharge().showApplePayResult(result: true);
      } else {  /// 支付失敗
        rootScaffoldMessengerKey.currentState?.showSnackBar(
          SnackBar(content: Text(startApplePayResult.message ?? '')),
        );
      }
    }
  }

  Future<void> linePay() async {
    final isAvailable = await TappayCharge().isLinePayAvailable();
    print(isAvailable);

    /// 1.獲取Prime
    final getLinePayPrimeResult = await TappayCharge().getLinePayPrime(returnUrl: 'smileEnergy://com.feibi.smileEnergy');
    print(getLinePayPrimeResult.toJson());

    /// 2.發起支付
    if (getLinePayPrimeResult.success) {
      final redirectLinePayResult = await TappayCharge().redirectLinePay(
        paymentUrl: 'https://sandbox-redirect.tappaysdk.com/redirect/15843de10a058ac545db4bdc95b26f1e057d48696e49977822fa742c736e73ce',
      );
      if (redirectLinePayResult.success) {  /// 支付成功

      } else {  /// 支付失敗
        rootScaffoldMessengerKey.currentState?.showSnackBar(
          SnackBar(content: Text(redirectLinePayResult.message ?? '')),
        );
      }
    }
  }

  Future<void> easyWallet() async {
    final isAvailable = await TappayCharge().isEasyWalletAvailable();
    print(isAvailable);

    /// 1.獲取Prime
    /// 方法1：URL Scheme
    // final getEasyWalletPrimeResult = await TappayCharge().getEasyWalletPrime(returnUrl: 'smileEnergy://com.feibi.smileEnergy');

    /// 方法2：Universal Link
    final getEasyWalletPrimeResult = await TappayCharge().getEasyWalletPrime(returnUrl: 'https://api.mc.sunflower-eco.casaloma.cc');

    print(getEasyWalletPrimeResult.toJson());
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      scaffoldMessengerKey: rootScaffoldMessengerKey,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('Running on: $_platformVersion\n'),

              FilledButton(
                onPressed: cardPay,
                child: const Text('Card Pay'),
              ),

              FilledButton(
                onPressed: applePay,
                child: const Text('Apply Pay'),
              ),

              FilledButton(
                onPressed: linePay,
                child: const Text('Line Pay'),
              ),

              FilledButton(
                onPressed: easyWallet,
                child: const Text('Easy Wallet'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
